import React from "react";
import { useSelector, useDispatch } from "react-redux";

import {
  action_plus,
  action_minus,
  action_plusIfOdd,
  action_plusAsync,
} from "../../redux/count_reducer";

export default function Count() {
  const selectedRef = React.createRef();
  const count = useSelector((state) => state.counter.value);
  const dispatch = useDispatch();

  const plus = () => {
    const { value } = selectedRef.current;
    dispatch(action_plus(parseInt(value)));
  };
  const minus = () => {
    const { value } = selectedRef.current;
    dispatch(action_minus(parseInt(value)));
  };
  const plusIfOdd = () => {
    const { value } = selectedRef.current;
    dispatch(action_plusIfOdd(parseInt(value)));
  };
  const plusAsync = () => {
    const { value } = selectedRef.current;
    setTimeout(() => {
      dispatch(action_plusAsync(parseInt(value)));
    }, 2000);
  };

  return (
    <div>
      <p>结果: {count}</p>
      <select ref={selectedRef}>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
      </select>
      &nbsp;
      <button onClick={plus}>+</button>&nbsp;
      <button onClick={minus}>-</button>&nbsp;
      <button onClick={plusIfOdd}>是奇数才加</button>&nbsp;
      <button onClick={plusAsync}>异步加</button>&nbsp;
    </div>
  );
}
